﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.Utils;
using DevExpress.XtraLayout;
using Pharmacy;
using VCS.Data;
using VCS.Entities;
using VCS.Settings.BusinessLayer;
using VCS.Windows.Forms.Properties;
using WinUtilities;
using WinUtilities.Class;

namespace VCS.Windows.Forms.Form.Main
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FormPatient : DevExpress.XtraEditors.XtraForm
    {
        /// <summary>
        /// 
        /// </summary>

        private List<Control> _requireValue;
        /// <summary>
        /// 
        /// </summary>
        public bool mIsInsert = true;
        private Patient ObjPatient;
        /// <summary>
        /// 
        /// </summary>
        public FormPatient()
        {
            InitializeComponent();
            HighLightControl();
            //Fill Data
            var companies = DataRepository.CompanyProvider.GetAll();
            var countries = DataRepository.CountryProvider.GetAll();
            var memberTypes = DataRepository.MemberTypeProvider.GetAll();
            //companies.Insert(0, new Company { CompanyCode = null, CompanyName = "" });
            //Setup SearchLookUpEdit
            txtCompany.Properties.DataSource = companies;
            txtCompany.Properties.DisplayMember = "CompanyName";
            txtCompany.Properties.ValueMember = "CompanyCode";
            txtCompany.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;

            txtNationality.Properties.DataSource = countries;
            txtNationality.Properties.DisplayMember = "CitizenName";
            txtNationality.Properties.ValueMember = "CitizenName";
            txtNationality.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;

            txtHomeCountry.Properties.DataSource = countries;
            txtHomeCountry.Properties.DisplayMember = "CountryName";
            txtHomeCountry.Properties.ValueMember = "CountryName";
            txtHomeCountry.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;

            txtMemberType.Properties.DataSource = memberTypes;
            txtMemberType.Properties.DisplayMember = "MemberType";
            txtMemberType.Properties.ValueMember = "MemberType";
            txtMemberType.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;
            //Event For itemControl
            itemControlsSearch.DisplaySearchResult += DisplaySearchResult;
            itemControlsSearch.DisplayLogResult += DisplayLogResult;
            itemControlsSearch.ButtonCancelClick += itemControlsSearch_ButtonCancelClick;
            itemControlsSearch.ButtonCloseClick += itemControlsSearch_ButtonCloseClick;
            itemControlsSearch.ButtonDeleteClick += itemControlsSearch_ButtonDeleteClick;
            itemControlsSearch.ButtonEditClick += itemControlsSearch_ButtonEditClick;
            itemControlsSearch.ButtonFindClick += itemControlsSearch_ButtonFindClick;
            itemControlsSearch.ButtonNewClick += itemControlsSearch_ButtonNewClick;
            itemControlsSearch.ButtonSaveClick += itemControlsSearch_ButtonSaveClick;

            //Allow Null In DateEdit
            txtDOB.Properties.AllowNullInput = DefaultBoolean.True;
            txtDOB.Properties.NullDate = null;
            txtMembershipSOSExpDate.Properties.AllowNullInput = DefaultBoolean.True;
            txtMembershipSOSExpDate.Properties.NullDate = null;
            txtInsuranceCardExpDate.Properties.AllowNullInput = DefaultBoolean.True;
            txtInsuranceCardExpDate.Properties.NullDate = null;

            // Passing hotkey from Form to itemControlSearch
            //KeyDown += GlobalKeyDown;
            //Lock Layout
            DisableLayout(false);
        }


        private void DisableLayout(bool IsEnabled)
        {
            GlobalUtilities.ControlEnable(IsEnabled, Layout_Info, layoutInfocard, Layout_Administrator, layoutContact,
                                          layoutResident, layoutMembership, layoutEmployment);
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (GlobalUtilities.GlobalProcessCmdKey(this, itemControlsSearch.TrappedKeyDown, ref msg, keyData))
                return true;
            return base.ProcessCmdKey(ref msg, keyData);
        }

        /// <summary>
        /// 
        /// </summary>
        public void ClearTextBox()
        {
            GlobalUtilities.ClearTextbox(Layout_Info, layoutInfocard, Layout_Administrator, layoutContact, layoutResident, layoutMembership, layoutEmployment);
        }

        private void HighLightControl()
        {
            IntializeRequireValue();
            foreach (LayoutControlItem item in Layout_Info.Root.Items)
            {
                if (_requireValue.Contains(item.Control))
                    item.AppearanceItemCaption.ForeColor = CommonColors.GetCriticalColor(UserLookAndFeel.Default.ActiveLookAndFeel);
            }
        }

        private void IntializeRequireValue()
        {
            _requireValue = new List<Control> { txtDOB, txtSex, txtFirstName, txtLastName, txtNationality, txtMemberType };
        }

        void GetInfo(ref Patient objPatient)
        {
            if (mIsInsert)
            {
                objPatient = new Patient { CreateUser = Program.GlobalUser.UserId, CreateDate = DateTime.Now };
                string patientCode = "";
                DataRepository.PatientProvider.GetPatientCode(ServiceFacade.SettingsHelper.LocationCode, txtLastName.Text.Substring(0, 1), ref patientCode);
                ObjPatient.PatientCode = patientCode;
            }
            objPatient.FirstName = txtFirstName.Text;
            objPatient.LastName = txtLastName.Text;
            objPatient.MiddleName = txtMiddleName.Text;
            objPatient.DateOfBirth = txtDOB.DateTime;
            objPatient.Sex = "F";
            if (txtSex.SelectedItem.ToString() == "Male")
                objPatient.Sex = "M";
            objPatient.MemberType = txtMemberType.EditValue.ToString();
            objPatient.Nationality = txtNationality.EditValue.ToString();
            objPatient.HomeStreet = txtAddress.Text;
            objPatient.HomeWard = txtWard.Text;
            objPatient.HomeDistrict = txtDistrict.Text;
            objPatient.HomeCity = txtCity.Text;
            if (txtHomeCountry.EditValue != null)
                objPatient.HomeCountry = txtHomeCountry.EditValue.ToString();
            objPatient.HomePhone = txtHomephone.Text;
            objPatient.MobilePhone = txtMobilephone.Text;
            objPatient.CompanyPhone = txtCompanyphone.Text;
            objPatient.Fax = txtFax.Text;
            objPatient.EmailAddress = txtEmail.Text;
            if (txtCompany.EditValue != null)
                objPatient.CompanyCode = txtCompany.EditValue.ToString();
            objPatient.ValidCorporate = checkValidCorporate.Checked;
            objPatient.InsuranceCardNumber = txtInsuranceCardNumber.Text;
            if (txtInsuranceCardExpDate.EditValue != null)
                objPatient.InsuranceCardExpDate = txtInsuranceCardExpDate.DateTime;
            objPatient.MembershipSosNumber = txtMembershipSOSNumber.Text;
            if (txtMembershipSOSExpDate.EditValue != null)
                objPatient.MembershipSosExpDate = txtMembershipSOSExpDate.DateTime;
            objPatient.Remark = txtRemark.Text;
        }

        /// <summary>
        /// Get Data From Form
        /// </summary>
        /// <param name="objPatient"></param>
        public void LoadUpdate(Patient objPatient)
        {
            DataRepository.PatientProvider.DeepLoad(objPatient);
            txtFirstName.Text = objPatient.FirstName;
            txtLastName.Text = objPatient.LastName;
            txtMiddleName.Text = objPatient.MiddleName;
            txtNationality.EditValue = objPatient.Nationality;
            txtPatientCode.Text = objPatient.PatientCode;
            txtDOB.EditValue = objPatient.DateOfBirth;
            txtSex.SelectedItem = "Female";
            if (objPatient.Sex == "M")
                txtSex.SelectedItem = "Male";
            txtMemberType.EditValue = objPatient.MemberType;
            txtCompany.EditValue = objPatient.CompanyCode;
            txtNationality.EditValue = objPatient.Nationality;
            txtAddress.Text = objPatient.HomeStreet;
            txtWard.Text = objPatient.HomeWard;
            txtDistrict.Text = objPatient.HomeDistrict;
            txtCity.Text = objPatient.HomeCity;
            txtHomeCountry.EditValue = objPatient.HomeCountry;
            if (objPatient.CompanyCodeSource != null)
            {
                txtCompanyName.Text = objPatient.CompanyCodeSource.CompanyName;
                txtCompanyAddress.Text = objPatient.CompanyCodeSource.Address;
                txtTAXNumber.Text = objPatient.CompanyCodeSource.TaxNumber;
                txtCompanyTelephone.Text = objPatient.CompanyCodeSource.CompanyTel;
                txtContactPerson.Text = objPatient.CompanyCodeSource.Attn;
                txtContactPhone.Text = objPatient.CompanyCodeSource.AttnPhone;
            }
            txtTelephone.Text = !string.IsNullOrEmpty(objPatient.MobilePhone)
                                    ? objPatient.MobilePhone
                                    : !string.IsNullOrEmpty(objPatient.HomePhone)
                                          ? objPatient.HomePhone
                                          : objPatient.CompanyPhone;
            txtMobilephone.Text = objPatient.MobilePhone;
            txtHomephone.Text = objPatient.HomePhone;
            txtCompanyphone.Text = objPatient.CompanyPhone;
            txtFax.Text = objPatient.Fax;
            txtEmail.Text = objPatient.EmailAddress;
            checkValidCorporate.Checked = objPatient.ValidCorporate;
            txtInsuranceCardNumber.Text = objPatient.InsuranceCardNumber;
            txtInsuranceCardExpDate.EditValue = objPatient.InsuranceCardExpDate;
            txtMembershipSOSNumber.Text = objPatient.MembershipSosNumber;
            txtMembershipSOSExpDate.EditValue = objPatient.MembershipSosExpDate;
            txtRemark.Text = objPatient.Remark;
        }

        void DisplaySearchResult(object resultRow)
        {
            ObjPatient = (Patient)resultRow;
            LoadUpdate(ObjPatient);
        }

        DataSet DisplayLogResult()
        {
            return GlobalUtilities.ReadLog(ObjPatient, DataRepository.Provider.ExecuteDataSet);
        }

        private void SetDefaultValue()
        {
            txtSex.SelectedItem = Resources.DefaultSex;
            txtMemberType.EditValue = Resources.DefaultMemberType;
        }

        private IBindingListView itemControlsSearch_ButtonFindClick()
        {
            int count;
            // Search Methods
            TList<Patient> searchResult = DataRepository.PatientProvider.GetPaged(itemControlsSearch.WhereExpression, "", 0, 100, out count);
            return searchResult;
        }

        private CommandStatus itemControlsSearch_ButtonSaveClick(object sender, EventArgs e)
        {
            bool check = GlobalUtilities.CheckInfo(_requireValue, Layout_Info);
            if (check)
            {
                if (mIsInsert)
                {
                    if (MessageBox.Show(Resources.InsertNotice, Resources.InsertMenu,
                               MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        GetInfo(ref ObjPatient);
                        ObjPatient.UpdateUser = Program.GlobalUser.UserId;
                        ObjPatient.UpdateDate = DateTime.Now;
                        DataRepository.PatientProvider.Insert(ObjPatient);
                        txtPatientCode.Text = ObjPatient.PatientCode;
                        DisableLayout(false);
                        return CommandStatus.Inserted;
                    }
                    return CommandStatus.Canceled;
                }
                if (MessageBox.Show(Resources.UpdateNotice, Resources.UpdateMenu,
                           MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var oldPatient = ObjPatient.Clone();
                    GetInfo(ref ObjPatient);
                    GlobalUtilities.WriteLog(oldPatient, ObjPatient, Program.GlobalUser.UserId, DataRepository.Provider.ExecuteDataSet);
                    ObjPatient.UpdateUser = Program.GlobalUser.UserId;
                    ObjPatient.UpdateDate = DateTime.Now;
                    DataRepository.PatientProvider.Update(ObjPatient);
                    DisableLayout(false);
                    return CommandStatus.Updated;
                }
                return CommandStatus.Canceled;
            }
            return CommandStatus.Canceled;
        }

        private void itemControlsSearch_ButtonNewClick(object sender, EventArgs e)
        {
            ClearTextBox();
            mIsInsert = true;
            DisableLayout(true);
            SetDefaultValue();
            txtLastName.Focus();
        }

        private void itemControlsSearch_ButtonEditClick(object sender, EventArgs e)
        {
            mIsInsert = false;
            DisableLayout(true);
            txtLastName.Focus();
        }

        private void txtCompany_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "cbbCompany")
            {
                var formCompany = new FormCompany();
                formCompany.Closed += FormCompanyClosed;
                formCompany.ShowDialog();
            }
        }

        private void FormCompanyClosed(object sender, EventArgs eventArgs)
        {
            var companies = DataRepository.CompanyProvider.GetAll();
            txtCompany.Properties.DataSource = companies;
        }

        private CommandStatus itemControlsSearch_ButtonDeleteClick(object sender, EventArgs e)
        {
            if (MessageBox.Show(Resources.DeleteNotice, Resources.DeleteMenu,
                                       MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DataRepository.PatientProvider.Delete(ObjPatient);
                ClearTextBox();
                return CommandStatus.Deleted;
            }
            return CommandStatus.Canceled;
        }

        private void itemControlsSearch_ButtonCloseClick(object sender, EventArgs e)
        {
            Close();
        }

        private CommandStatus itemControlsSearch_ButtonCancelClick(object sender, EventArgs e)
        {
            bool warning = MessageBox.Show(Resources.CancelNotice, Resources.CancelMenu, MessageBoxButtons.YesNoCancel) == DialogResult.Yes;
            if (warning)
            {
                if (mIsInsert)
                {
                    ClearTextBox();
                    DisableLayout(false);
                    return CommandStatus.Inserted;
                }
                LoadUpdate(ObjPatient);
                DisableLayout(false);
                return CommandStatus.Updated;
            }
            return CommandStatus.Canceled;
        }
    }
}